﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using Markdig;
using Markdig.Extensions.Bootstrap;
using Markdig.Extensions.Emoji;
using Markdig.Extensions.TaskLists;
using Markdig.SyntaxHighlighting;

namespace WindowsFormsApp1
{
    public partial class MD2Html : Form
    {
        public MD2Html()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DirectoryInfo mdDir = new DirectoryInfo(txb_md.Text);

            if (!Directory.Exists(txb_html.Text))
            {
                Directory.CreateDirectory(txb_html.Text); //建立文件夹
            }

            var builder = (new Markdig.MarkdownPipelineBuilder());
            builder.Extensions.Add(new Markdig.Extensions.Tables.PipeTableExtension());//添加MarkDown对table的扩展
            builder.Extensions.Add(new BootstrapExtension());//添加bootstrap样式
            builder.Extensions.Add(new TaskListExtension());//添加github任务列表样式
            builder.Extensions.Add(new EmojiExtension(EmojiMapping.DefaultEmojisAndSmileysMapping));//添加Emoji表情支持
            builder.Extensions.Add(new SyntaxHighlightingExtension());//语法高亮

            var pipeline = builder.Build();

            // Configure the pipeline with all advanced extensions active
            //var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();


            IEnumerable<FileInfo> mdList;
            string html;
            string savePath;
            mdList = mdDir.EnumerateFiles("*.md").OrderBy(p => p.Name);
            foreach (var md in mdList)
            {
                //md转html

                html = Markdown.ToHtml(
                    TxtHelper.ReadTxt(txb_md.Text + "\\" + md.Name), pipeline
                    );
              
                //下载网络图片
                html=DownLoadFileBllcs.SyncHtmlByUrl(html, txb_html.Text);
                //替换github链接为本地链接
                savePath = txb_html.Text + "\\" + Path.GetFileNameWithoutExtension(md.Name) + ".html";
                ReplaceLinkStr(html, savePath);
            }

            MessageBox.Show("更改完成！");
        }



        string xpathStr = "//a[contains(@href,'/wiki/')]";//获取右侧导航a标签(只包含路径/wiki/)

        /// <summary>
        /// 替换github链接标签
        /// </summary>
        private void ReplaceLinkStr(string html, string filePath)
        {

            if (html.Length == 0) return;

            StringBuilder sbHtml = new StringBuilder(html);

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);
            HtmlNodeCollection pageNode = doc.DocumentNode.SelectNodes(xpathStr);
            if (pageNode != null)
            {
                string href;
                string link;//段链接
                string str1;//被替换后的字符串
                foreach (var pn in pageNode)
                {
                    href = pn.Attributes["href"]?.Value;

                    if (!string.IsNullOrEmpty(href))
                    {
                        str1 = href.Substring(href.IndexOf("/wiki/") + "/wiki/".Length);
                        if (str1.Contains("#"))
                        {
                            string[] tempStrs = str1.Split('#');
                            str1 = tempStrs[0] + ".html#" + tempStrs[1];
                        }
                        else if (str1.Contains("?"))
                        {
                            string[] tempStrs = str1.Split('?');
                            str1 = tempStrs[0] + ".html?" + tempStrs[1];
                        }
                        else
                        {
                            str1 = str1 + ".html";
                        }

                        sbHtml.Replace(href, str1);
                    }
                }
            }

            TxtHelper.WriteTxt(filePath, sbHtml.ToString());
        }

        /// <summary>
        /// 获取短链接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private string GetLinkByUrl(string url)
        {
            if (url.Contains("#"))
            {   //github.com/wiki/abc#id
                return StringHelper.GetBetweenStr(url, "/wiki/", "#");
            }

            if (url.Contains("?"))
            {   //github.com/wiki/abc?id
                return StringHelper.GetBetweenStr(url, "/wiki/", "?");
            }

            int indexNum = url.IndexOf("/wiki/") + "/wiki/".Length;
            return url.Substring(indexNum);
        }

    }
}
